/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_cyclonedds/utils/DomainConfigMap.hpp"
#include "dal_cyclonedds/utils/log.hpp"

DomainConfigMap* DomainConfigMap::singleton_ = nullptr;

DomainConfigMap::DomainConfigMap() {}

DomainConfigMap* DomainConfigMap::GetInstance()
{
    if (singleton_ == nullptr) {
        singleton_ = new DomainConfigMap();
    }
    return singleton_;
}

void DomainConfigMap::AddDomainConfig(uint32_t domainId, dds_entity_t domainConfig)
{
    std::lock_guard<std::mutex> lkg(mutex_);
    if (map_.find(domainId) == map_.end()) {
        map_[domainId] = std::make_pair(domainConfig, 1);
    } else {
        if (domainConfig != map_[domainId].first) {
            LOG_ERROR_WITH_LOCATION() << "test error log with location" << LOG_ENDL;
            return;
        }
        ++(map_[domainId].second);
    }
}

dds_entity_t DomainConfigMap::GetDomainConfig(uint32_t domainId)
{
    std::lock_guard<std::mutex> lkg(mutex_);
    if (map_.find(domainId) != map_.end()) {
        if (map_[domainId].second > 0) {
            return map_[domainId].first;
        }
    }
    return -1;
}

bool DomainConfigMap::DeleteDomainConfig(uint32_t domainId)
{
    std::lock_guard<std::mutex> lkg(mutex_);
    if (map_.find(domainId) != map_.end()) {
        --(map_[domainId].second);
        if (map_[domainId].second == 0) {
            dds_entity_t config = map_[domainId].first;
            map_.erase(domainId);
            if (dds_delete(config) != DDS_RETCODE_OK) {
                return false;
            }
        }
    }
    return true;
}